<template>
  <div class="app-container">
    <h2>自动活动配置</h2>
    <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="180px">
      <el-form-item label="开启">
        <el-switch
          v-model="form.runStatus"
          :active-value="1"
          :inactive-value="0">
        </el-switch>
      </el-form-item>
      <el-form-item label="活动名称">
        <el-input v-model="form.name" style="width: 370px;" />
      </el-form-item>
      <el-form-item label="服务器列表">
        <el-checkbox-group v-model="selectedServerIds">
          <el-checkbox
            v-for="server in serverlistData"
            :key="server.id"
            :label="server.id"
          >
            {{ server.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="换牌所需基础筹码数量">
        <el-input v-model="form.changePokerBaseNum" style="width: 370px;" />
      </el-form-item>
      <el-form-item label="每次换牌需要增加筹码数量">
        <el-input v-model="form.changePokerAddNum" style="width: 370px;" />
      </el-form-item>
      <el-form-item label="免费换牌次数">
        <el-input v-model="form.activeFreeChage" style="width: 370px;" />
      </el-form-item>
      <el-form-item label="最大换牌次数">
        <el-input v-model="form.activeMaxChage" style="width: 370px;" />
      </el-form-item>
      <el-form-item label="活动描述">
        <el-input v-model="form.activateDesc" style="width: 370px;" />
      </el-form-item>
      <el-form-item label="活动奖励">
        <el-button type="primary" @click="awardAdd = true">奖励配置</el-button>
        <el-table :data="showAward" style="width: 100%" max-height="400"
                  :default-sort="{ prop: 'rank', order: 'ascending' }">
          <el-table-column prop="rank" label="排名" sortable></el-table-column>
          <el-table-column label="奖励内容">
            <template slot-scope="scope">
              {{ scope.row.content.map(i => `${i.goodName} × ${i.num}`).join('，') }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="deleteAward(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="doForm">保存</el-button>
        <el-button type="primary" @click="testTaskGenApi">手动生成</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 奖励配置对话框 -->
    <el-dialog title="新增/编辑奖励" :visible.sync="awardAdd" width="40%">
      <el-form ref="awardForm" :model="currentAward" :rules="awardRules" size="small" label-width="120px">
        <el-form-item label="排名" prop="rank">
          <el-input v-model.number="currentAward.rank" style="width: 200px;" />
        </el-form-item>

        <!-- 多个商品配置 -->
        <div v-for="(item, index) in currentAward.content" :key="index">
          <el-form-item label="物品" :prop="'content.' + index + '.goodId'" :rules="{ required: true, message: '请选择物品', trigger: 'change' }">
            <el-select
              v-model="item.goodId"
              style="width: 200px;"
              filterable
              placeholder="请选择物品"
              @change="(val) => handleGoodChange(val, index)"
            >
              <el-option
                v-for="good in goodlistData"
                :key="good.goodId"
                :label="good.goodName"
                :value="good.goodId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="数量" :prop="'content.' + index + '.num'" :rules="{ required: true, message: '请输入数量', trigger: 'blur' }">
            <el-input v-model="item.num" style="width: 200px;" />
          </el-form-item>
        </div>

        <el-button type="primary" @click="addAwardItem">+ 增加</el-button>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="awardAdd = false">取消</el-button>
        <el-button type="primary" @click="saveAward">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { edit, get1 } from '@/api/system/autoPokerActivateConfig'
import { randmoCard } from '@/api/system/pokerActivateInfo'
import { goodList } from '@/api/system/pokerGoodInfo'
import { serverList,testTaskGen } from '@/api/system/pokerActivateInfo'


export default {
  name: 'AutoPokerActivateConfig',
  data() {
    return {
      awardAdd: false,
      currentAwardIndex: -1,
      serverlistData: [],
      selectedServerIds: [],
      currentAward: {
        rank: '',
        content: [
          { goodId: '', num: '', goodName: '' }
        ]
      },
      showAward: [],
      form: {
        runStatus: 0,
        name: '',
        changePokerBaseNum: '',
        changePokerAddNum: '',
        activeFreeChage: '',
        activeMaxChage: '',
        activateDesc: '',
        awardContent: "[]",
        selectedServerIds: ""
      },
      rules: {},
      awardRules: {
        rank: [{ required: true, message: '请输入排名', trigger: 'blur' }],
        goodId: [{ required: true, message: '请选择物品', trigger: 'blur' }],
        num: [{ required: true, message: '请输入数量', trigger: 'blur' }]
      },
      goodlistData: []
    }
  },
  computed: {
    parsedAwardContent() {
      try {
        return JSON.parse(this.form.awardContent) || [];
      } catch (e) {
        return [];
      }
    }
  },
  created() {
    this.getForm()
    this.getgoodList()
    this.getserverList()
  },
  methods: {
    handleGoodChange(val, index) {
      const selectedGood = this.goodlistData.find(good => good.goodId === val);
      if (selectedGood) {
        this.currentAward.content[index].goodName = selectedGood.goodName;
      } else {
        this.currentAward.content[index].goodName = '';
      }
    },
    // 添加一个商品配置
    addAwardItem() {
      this.currentAward.content.push({ goodId: '', num: '', goodName: "" });
    },

    // 删除某个商品配置
    removeAwardItem(index) {
      this.currentAward.content.splice(index, 1);
    },
    getserverList() {
      serverList().then((res) => {
        this.serverlistData = res;
      })
    },
    getgoodList() {
      goodList().then((res) => {
        this.goodlistData = res;
      })
    },
    randmoCardApi(poker) {
      randmoCard().then((res) => {
        if (poker == 1) {
          this.$message.success(res)
          this.form.pubPoker1 = res
        } else if (poker == 2) {
          this.$message.success(res)
          this.form.pubPoker2 = res
        }
      })
    },
    getForm() {
      get1().then((res) => {
        this.form = res;
        console.log(this.form.awardContent, "this.form.awardContent");
        this.showAward = JSON.parse(this.form.awardContent);
        console.log(this.showAward, "showAward");

        // 设置选中的服务器 ID
        if (this.form.serverIds) {
          this.selectedServerIds = this.form.serverIds.split(',').map(id => parseInt(id));
        }
      })
    },
    doForm() {
      // 提交表单数据到后端
      const formData = { ...this.form };
      formData.awardContent = JSON.stringify(this.showAward);
      formData.serverIds = this.selectedServerIds.join(',');
      console.log(formData);
      edit(formData)
        .then(() => {
          this.$message.success('保存成功')
        })
        .catch(error => {
          console.error('提交失败', error)
          this.$message.error('保存失败，请重试')
        })
    },
    resetForm() {
      this.$refs.form.resetFields();
      this.form.awardContent = "[]";
      this.selectedServerIds = [];
      this.showAward = [];
    },
    saveAward() {
      this.showAward.push(this.currentAward);
      this.currentAward = {
        rank: '',
        content: [
          { goodId: '', num: '', goodName: '' }
        ]
      };
      this.awardAdd = false;
    },
    deleteAward(index) {
      this.$confirm('确定要删除该奖励配置吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.showAward.splice(index, 1); // 删除数组中的对应项
      }).catch(() => {
        // 取消操作
      });
    },
    testTaskGenApi(){
        testTaskGen().then((res) => {
        this.$message.success('生成测试')
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f9fafc;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-weight: bold;
}

.el-input,
.el-select,
.el-date-picker {
  width: 100%;
}

.el-button {
  margin-right: 10px;
}

.el-table {
  margin-top: 10px;
  margin-bottom: 20px;
}
</style>



